﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Application.Common;
using Application.Presentation;
using Interface.Clinical;
using Interface.SCM;

namespace IQCare.SCM
{
    public partial class frmPatientDrugDispense : Form
    {
        #region "Variables"
        DataSet XMLDS = new DataSet(); /// for All Masters ////
        DataSet XMLPharDS = new DataSet(); ///for Pharmacy Masters///                                       
        DataSet thePharmacyMaster = new DataSet();
        Int32 thePatientId=0;
        Int32 theOrderId=0;
        Int32 theReturnOrderId = 0;
        DateTime theDOB;
        /// <summary>
        /// Dispensing Variables
        /// </summary>
        Int32 theFunded = 0;
        Int32 theItemId = 0;
        Int32 theDispensingUnit = 0;
        Int32 theBatchId = 0;
        Int32 theAvailQty = 0;
        Int32 theStrength = 0;
        Int32 theItemType = 0;
        Int32 theProphylaxis = 0;
        decimal theCostPrice = 0;
        decimal theMargin = 0;
        decimal theBillAmt = 0;
        decimal theSellingPrice = 0;
        string theDispensingUnitName = "";
        string theGenericAbb = "";
        String theOrderStatus = "";

        decimal thePrecribeAmt = 0;
        ////////////
        /// <summary>
        /// GridControls
        /// </summary>
        TextBox theReturnQty = new TextBox();
        Int32 theCurrentRow = 0;
        ////////////////////////// 

        #endregion

        public frmPatientDrugDispense()
        {
            InitializeComponent();
        }
        private void Init_Form()
        {
            BindCombo();
            txtPatientIdentification.Text = "";
            txtFirstName.Text = "";
            txtLastName.Text = "";
            dtpDOB.CustomFormat = " ";
            cmbFacility.SelectedValue = GblIQCare.AppLocationId.ToString();
            dtDispensedDate.Text = GblIQCare.CurrentDate;
            dtpReturnDate.Text = GblIQCare.CurrentDate;
            cmbFacility.Enabled = false;
            lstSearch.Visible = false;
            cmdSave.Visible = false;
            grpExistingRec.Visible = false;
            Authentication();
        }
        private void Authentication()
        {
            if (GblIQCare.HasFunctionRight(ApplicationAccess.DrugDispense, FunctionAccess.Add, GblIQCare.dtUserRight) == false)
            {
                btnSave.Enabled = false;
            }
            if (GblIQCare.HasFunctionRight(ApplicationAccess.DrugDispense, FunctionAccess.Update, GblIQCare.dtUserRight) == false)
            {
                btnSave.Enabled = false;
            }
        }

        private void BindSearchGrid(DataTable theDT)
        {
            grdResultView.DataSource = null;
            grdResultView.AutoGenerateColumns = false;
            grdResultView.Columns.Clear();

            DataGridViewTextBoxColumn theCol1 = new DataGridViewTextBoxColumn();
            theCol1.HeaderText = "Last Name";
            theCol1.DataPropertyName = "lastname";
            theCol1.Width = 200;

            DataGridViewTextBoxColumn theCol2 = new DataGridViewTextBoxColumn();
            theCol2.HeaderText = "First Name";
            theCol2.DataPropertyName = "firstname";
            theCol2.Width = 200;

            DataGridViewTextBoxColumn theCol3 = new DataGridViewTextBoxColumn();
            theCol3.HeaderText = "IQ-Number";
            theCol3.DataPropertyName = "PatientId";
            theCol3.Width = 150;

            DataGridViewTextBoxColumn theCol4 = new DataGridViewTextBoxColumn();
            theCol4.HeaderText = "Sex";
            theCol4.DataPropertyName = "Name";
            theCol4.Width = 50;

            DataGridViewTextBoxColumn theCol5 = new DataGridViewTextBoxColumn();
            theCol5.HeaderText = "Date of Birth";
            theCol5.DataPropertyName = "dob";
            theCol5.Width = 120;

            DataGridViewTextBoxColumn theCol6 = new DataGridViewTextBoxColumn();
            theCol6.HeaderText = "Status";
            theCol6.DataPropertyName = "status";
            theCol6.Width = 60;

            DataGridViewTextBoxColumn theCol7 = new DataGridViewTextBoxColumn();
            theCol7.HeaderText = "Patient Location";
            theCol7.DataPropertyName = "FacilityName";
            theCol7.Width = 130;

            DataGridViewTextBoxColumn theCol8 = new DataGridViewTextBoxColumn();
            theCol8.HeaderText = "Ptn_Pk";
            theCol8.DataPropertyName = "Ptn_Pk";
            theCol8.Width = 10;
            theCol8.Visible = false;

            grdResultView.Columns.Add(theCol1);
            grdResultView.Columns.Add(theCol2);
            grdResultView.Columns.Add(theCol3);
            grdResultView.Columns.Add(theCol4);
            grdResultView.Columns.Add(theCol5);
            grdResultView.Columns.Add(theCol6);
            grdResultView.Columns.Add(theCol7);
            grdResultView.Columns.Add(theCol8);
            //grdResultView.Columns.Add(theCol9);
            //grdResultView.Columns.Add(theCol10);

            grdResultView.DataSource = theDT;
        }

        private void BindCombo()
        {
            XMLDS.ReadXml(GblIQCare.GetXMLPath() + "\\AllMasters.con");
            XMLPharDS.ReadXml(GblIQCare.GetXMLPath() + "\\DrugMasters.con"); 
            BindFunctions theBindManager = new BindFunctions();

            DataView theDV = new DataView(XMLDS.Tables["mst_Facility"]);
            theDV.RowFilter = "(DeleteFlag =0 or DeleteFlag is null)";
            DataTable theFacilityDT = theDV.ToTable();
            theBindManager.Win_BindCombo(cmbFacility, theFacilityDT, "FacilityName", "FacilityId");

            theDV = new DataView(XMLDS.Tables["mst_Decode"]);
            theDV.RowFilter = "CodeId = 4 and (DeleteFlag =0 or DeleteFlag is null)";
            DataTable theGender = theDV.ToTable();
            theBindManager.Win_BindCombo(cmbSex, theGender, "Name", "Id");

            theDV.RowFilter = "CodeId = 33 and (DeleteFlag =0 or DeleteFlag is null)";
            DataTable thePharProg = theDV.ToTable();
            theBindManager.Win_BindCombo(cmbprogram, thePharProg, "Name", "Id");
            
            theDV = new DataView(XMLPharDS.Tables["mst_Frequency"]);
            theDV.RowFilter = "(DeleteFlag =0 or DeleteFlag is null)";
            DataTable theDT = theDV.ToTable();
            theBindManager.Win_BindCombo(cmbFrequency, theDT, "Name", "Id");

        }

        private void frmPatientDrugDispense_Load(object sender, EventArgs e)
        {
            clsCssStyle theStyle = new clsCssStyle();
            theStyle.setStyle(this);
            Init_Form();
            tabDispense.SelectedTab = tabDispense.TabPages[0];
            txtPatientIdentification.Select();
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            string theSex = "";
            string theDOB = "";
            if (Convert.ToInt32(cmbSex.SelectedValue) > 0)
                theSex = cmbSex.SelectedValue.ToString();
            if (dtpDOB.CustomFormat == " ")
                theDOB = "01-01-1900";
            else
                theDOB = dtpDOB.Text;

            IPatientRegistration PatientManager = (IPatientRegistration)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPatientRegistration, BusinessProcess.Clinical");
            DataSet dsPatient = PatientManager.GetPatientSearchResults(Convert.ToInt32(cmbFacility.SelectedValue), txtLastName.Text, "", txtFirstName.Text, txtPatientIdentification.Text,
                theSex, Convert.ToDateTime(theDOB), "0");
            BindSearchGrid(dsPatient.Tables[0]);
        }

        private void dtpDOB_Enter(object sender, EventArgs e)
        {
            dtpDOB.CustomFormat = "dd-MMM-yyyy";
        }

        private void tabDispense_SelectedIndexChanged(object sender, EventArgs e)
        {
            if ((tabDispense.TabPages[1].Focus() == true || tabDispense.TabPages[2].Focus() == true) && thePatientId < 1)
            {
                IQCareWindowMsgBox.ShowWindow("PatientNotSelected", this);
                tabDispense.SelectedTab = tabDispense.TabPages[0];
                return;
            }
            if (tabDispense.TabPages[0].Focus() == true)
            {
                thePatientId = 0;
                this.Text = "Find Patient";
            }
            if (tabDispense.TabPages[1].Focus() == true)
            {
                DataView theDV = new DataView(XMLDS.Tables["Mst_Store"]);
                theDV.RowFilter = "Id="+GblIQCare.intStoreId.ToString();
                lblStoreName.Text = theDV[0]["Name"].ToString();
                cmdSave.Visible = true;
                theItemId = 0;
                theDispensingUnit = 0;
                theBatchId = 0;
                theCostPrice = 0;
                theMargin = 0;
                theBillAmt = 0;
                theDispensingUnitName = "";
                txtItemName.Text = "";
                txtBatchNo.Text = "";
                cmbFrequency.SelectedValue = "0";
                txtQtyDispensed.Text = "";
                txtExpirydate.Text = "";
                txtSellingPrice.Text = "";
                this.Text = "Dispense Drugs";

            }
            if (tabDispense.TabPages[2].Focus() == true)
            {
                DataView theDV = new DataView(XMLDS.Tables["Mst_Store"]);
                theDV.RowFilter = "Id=" + GblIQCare.intStoreId.ToString();
                lblReturnStoreName.Text = theDV[0]["Name"].ToString();
                cmdSave.Visible = true;
                this.Text = "Return Drugs";
                lblReturnDispensedDate.Text = "";
                lblReturnProgram.Text = ""; 
                IDrug thePharmacyManager = (IDrug)ObjectFactory.CreateInstance("BusinessProcess.SCM.BDrug, BusinessProcess.SCM");
                DataTable theDT = thePharmacyManager.GetPharmacyExistingRecord(thePatientId,GblIQCare.intStoreId);
                BindDrugReturnGrid(theDT);
                grdReturnDetail.DataSource = false;
                grdReturnDetail.Columns.Clear();
            }
        }

        private void grdResultView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            thePatientId = Convert.ToInt32(grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[7].Value);
            theDOB = Convert.ToDateTime(grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[4].Value);
            tabDispense.SelectedTab = tabDispense.TabPages[1];
            lblPatientName.Text = grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[0].Value.ToString() + ", " +
                grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[1].Value.ToString();
            lblReturnPatName.Text = grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[0].Value.ToString() + ", " +
                grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[1].Value.ToString();
            lblIQNumber.Text = grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[2].Value.ToString();
            lblReturnIQNumber.Text = grdResultView.Rows[grdResultView.CurrentRow.Index].Cells[2].Value.ToString();
            IDrug theDrugManager = (IDrug)ObjectFactory.CreateInstance("BusinessProcess.SCM.BDrug, BusinessProcess.SCM");
            thePharmacyMaster = theDrugManager.GetPharmacyDispenseMasters(thePatientId, GblIQCare.intStoreId);
            if (thePharmacyMaster.Tables[0].Rows.Count > 0)
            {
                if (thePharmacyMaster.Tables[0].Rows[0].IsNull("LastDispense"))
                {
                    lblDispDate.Text = "";
                    lblReturnLstDispDate.Text = "";
                }
                else
                {
                    lblDispDate.Text = ((DateTime)thePharmacyMaster.Tables[0].Rows[0]["LastDispense"]).ToString(GblIQCare.AppDateFormat.ToString());
                    lblReturnLstDispDate.Text = ((DateTime)thePharmacyMaster.Tables[0].Rows[0]["LastDispense"]).ToString(GblIQCare.AppDateFormat.ToString());
                }
                if (thePharmacyMaster.Tables[0].Rows[0].IsNull("LastRegimen"))
                {
                    lblLstRegimen.Text = "";
                    lblReturnLstRegimen.Text = "";
                }
                else
                {
                    lblLstRegimen.Text = thePharmacyMaster.Tables[0].Rows[0]["LastRegimen"].ToString();
                    lblReturnLstRegimen.Text = thePharmacyMaster.Tables[0].Rows[0]["LastRegimen"].ToString();
                }
            }
            else
            {
                lblDispDate.Text = "";
                lblLstRegimen.Text = "";
                lblReturnLstRegimen.Text = "";
                lblReturnLstDispDate.Text = "";
            }

            DataTable theDT = CreatePharmacyDispenseTable();
            BindPharmacyDispenseGrid(theDT);
            txtItemName.Select();
        }

        private DataTable CreatePharmacyDispenseTable()
        {
            DataTable theDT = new DataTable();
            theDT.Columns.Add("ItemId", Type.GetType("System.Int32"));
            theDT.Columns.Add("ItemName", Type.GetType("System.String"));
            theDT.Columns.Add("DispensingUnitId", Type.GetType("System.Int32"));
            theDT.Columns.Add("DispensingUnitName", Type.GetType("System.String"));
            theDT.Columns.Add("BatchId", Type.GetType("System.Int32"));
            theDT.Columns.Add("BatchNo", Type.GetType("System.String"));
            theDT.Columns.Add("StrengthId", Type.GetType("System.Int32"));
            theDT.Columns.Add("FrequencyId", Type.GetType("System.Int32"));
            theDT.Columns.Add("FrequencyName", Type.GetType("System.String"));
            theDT.Columns.Add("ExpiryDate", Type.GetType("System.DateTime"));
            theDT.Columns.Add("QtyDisp", Type.GetType("System.Int32"));
            theDT.Columns.Add("CostPrice", Type.GetType("System.Decimal"));
            theDT.Columns.Add("Margin", Type.GetType("System.Decimal"));
            theDT.Columns.Add("SellingPrice", Type.GetType("System.Decimal"));
            theDT.Columns.Add("BillAmount", Type.GetType("System.Decimal"));
            theDT.Columns.Add("Prophylaxis", Type.GetType("System.Int32"));
            theDT.Columns.Add("ItemType", Type.GetType("System.Int32"));
            theDT.Columns.Add("GenericAbb",Type.GetType("System.String"));

            //todo
            theDT.Columns.Add("OrderedQuantity", Type.GetType("System.String"));
            theDT.Columns.Add("DataStatus", Type.GetType("System.String"));

            DataColumn[] thePkey = new DataColumn[3];
            thePkey[0] = theDT.Columns["ItemId"];
            thePkey[1] = theDT.Columns["BatchId"];
            thePkey[2] = theDT.Columns["ExpiryDate"];
            theDT.PrimaryKey = thePkey;
            return theDT;
        }

        private void BindPharmacyDispenseGrid(DataTable theDT)
        {
            

            grdDrugDispense.DataSource = null;
            grdDrugDispense.Columns.Clear();
            grdDrugDispense.AutoGenerateColumns = false;    


            DataGridViewTextBoxColumn theCol1 = new DataGridViewTextBoxColumn();
            theCol1.HeaderText = "ItemId";
            theCol1.DataPropertyName = "ItemId";
            theCol1.Width = 10;
            theCol1.Visible = false;

            DataGridViewTextBoxColumn theCol2 = new DataGridViewTextBoxColumn();
            theCol2.HeaderText = "Drug Name";
            theCol2.DataPropertyName = "ItemName";
            theCol2.Width = 290;

            DataGridViewTextBoxColumn theCol3 = new DataGridViewTextBoxColumn();
            theCol3.HeaderText = "DispUnitId";
            theCol3.DataPropertyName = "DispensingUnitId";
            theCol3.Width = 10;
            theCol3.Visible = false;

            DataGridViewTextBoxColumn theCol4 = new DataGridViewTextBoxColumn();
            theCol4.HeaderText = "Dispensing Unit";
            theCol4.DataPropertyName = "DispensingUnitName";
            theCol4.Width = 80;

            DataGridViewTextBoxColumn theCol5 = new DataGridViewTextBoxColumn();
            theCol5.HeaderText = "BatchId";
            theCol5.DataPropertyName = "BatchId";
            theCol5.Width = 10;
            theCol5.Visible = false;

            DataGridViewTextBoxColumn theCol6 = new DataGridViewTextBoxColumn();
            theCol6.HeaderText = "Batch No";
            theCol6.DataPropertyName = "BatchNo";
            theCol6.Width = 80;

            DataGridViewTextBoxColumn theCol7 = new DataGridViewTextBoxColumn();
            theCol7.HeaderText = "Expiry Date";
            theCol7.DataPropertyName = "ExpiryDate";
            theCol7.Width = 80;

            DataGridViewTextBoxColumn theCol8 = new DataGridViewTextBoxColumn();
            theCol8.HeaderText = "Quantity Dispensed";
            theCol8.DataPropertyName = "QtyDisp";
            theCol8.Width = 80;

            DataGridViewTextBoxColumn theCol9 = new DataGridViewTextBoxColumn();
            theCol9.HeaderText = "CostPrice";
            theCol9.DataPropertyName = "CostPrice";
            theCol9.Width = 10;
            theCol9.Visible = false;

            DataGridViewTextBoxColumn theCol10 = new DataGridViewTextBoxColumn();
            theCol10.HeaderText = "Margin";
            theCol10.DataPropertyName = "Margin";
            theCol10.Width = 10;
            theCol10.Visible = false;

            DataGridViewTextBoxColumn theCol11 = new DataGridViewTextBoxColumn();
            theCol11.HeaderText = "Selling Price";
            theCol11.DataPropertyName = "SellingPrice";
            theCol11.Width = 80;

            DataGridViewTextBoxColumn theCol12 = new DataGridViewTextBoxColumn();
            theCol12.HeaderText = "Bill Amount";
            theCol12.DataPropertyName = "BillAmount";
            theCol12.Width = 80;

            DataGridViewTextBoxColumn theCol13 = new DataGridViewTextBoxColumn();
            theCol13.HeaderText = "StrengthId";
            theCol13.DataPropertyName = "StrengthId";
            theCol13.Width = 10;
            theCol13.Visible = false;

            DataGridViewTextBoxColumn theCol14 = new DataGridViewTextBoxColumn();
            theCol14.HeaderText = "Frequency";
            theCol14.DataPropertyName = "FrequencyId";
            theCol14.Width = 10;
            theCol14.Visible = false;

            DataGridViewTextBoxColumn theCol15 = new DataGridViewTextBoxColumn();
            theCol15.HeaderText = "Frequency";
            theCol15.DataPropertyName = "FrequencyName";
            theCol15.Width = 80;

            //todo

            DataGridViewTextBoxColumn theCol16 = new DataGridViewTextBoxColumn();
            theCol16.HeaderText = "Quantity Prescribed";
            theCol16.DataPropertyName = "OrderedQuantity";
            theCol16.Width = 80;

            DataGridViewTextBoxColumn theCol17 = new DataGridViewTextBoxColumn();
            theCol17.HeaderText = "DataStatus";
            theCol17.DataPropertyName = "DataStatus";
            theCol17.Width = 10;
            theCol17.Visible = false;
            
            grdDrugDispense.Columns.Add(theCol1);
            grdDrugDispense.Columns.Add(theCol2);
            grdDrugDispense.Columns.Add(theCol3);
            grdDrugDispense.Columns.Add(theCol4);
            grdDrugDispense.Columns.Add(theCol5);
            grdDrugDispense.Columns.Add(theCol6);
            grdDrugDispense.Columns.Add(theCol7);
            grdDrugDispense.Columns.Add(theCol15);
            grdDrugDispense.Columns.Add(theCol16);
            grdDrugDispense.Columns.Add(theCol8);
            // add
            grdDrugDispense.Columns.Add(theCol9);
            grdDrugDispense.Columns.Add(theCol10);
            grdDrugDispense.Columns.Add(theCol11);
            grdDrugDispense.Columns.Add(theCol12);
            grdDrugDispense.Columns.Add(theCol13);
            grdDrugDispense.Columns.Add(theCol14);

            //todo
          //  grdDrugDispense.Columns.Add(theCol16);
            grdDrugDispense.Columns.Add(theCol17);

            grdDrugDispense.DataSource = theDT;
        }

        private void lstSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                lstSearch_DoubleClick(sender, e);
            }
        }

        private void txtItemName_KeyUp(object sender, KeyEventArgs e)
        {
            if (txtItemName.Text != "")
            {
                lstSearch.Visible = true;
                lstSearch.Width = 800;
                lstSearch.Left = txtItemName.Left-70;
                lstSearch.Top = splitContainer2.Top + txtItemName.Top + txtItemName.Height;
                lstSearch.Height = 300;
                DataView theDV = new DataView(thePharmacyMaster.Tables[1]);
                theDV.RowFilter = "DrugName like '%" + txtItemName.Text + "%'";
                if (theDV.Count > 0)
                {
                    DataTable theDT = theDV.ToTable();
                    BindFunctions theBindManager = new BindFunctions();
                    theBindManager.Win_BindListBox(lstSearch, theDT, "DisplayItem", "DisplayItemId");
                }
                else
                {
                    lstSearch.DataSource = null;
                }

            }
            else
            {
                lstSearch.Visible = false;
            }
            if (e.KeyCode == Keys.Down)
                lstSearch.Select();
        }

        private void lstSearch_DoubleClick(object sender, EventArgs e)
        {
            if (lstSearch.SelectedValue!="")
            {
                string[] theId = lstSearch.SelectedValue.ToString().Split('-');
                theItemId = Convert.ToInt32(theId.GetValue(0));
                DataView theDV = new DataView(thePharmacyMaster.Tables[1]);
                theDV.RowFilter = "Drug_Pk = " + theItemId.ToString() + " and BatchId = "+ theId.GetValue(1).ToString() + " and ExpiryDate='"+theId.GetValue(2).ToString()+"'";
                txtItemName.Text = theDV[0]["DrugName"].ToString();
                txtBatchNo.Text = theDV[0]["BatchNo"].ToString();
                theBatchId = Convert.ToInt32(theDV[0]["BatchId"]);
                txtExpirydate.Text = ((DateTime)theDV[0]["ExpiryDate"]).ToString(GblIQCare.AppDateFormat);
                theSellingPrice = Convert.ToDecimal(theDV[0]["SellingPrice"]);
                theCostPrice = Convert.ToDecimal(theDV[0]["CostPrice"]);
                theMargin = Convert.ToDecimal(theDV[0]["DispensingMargin"]);
                theDispensingUnit = Convert.ToInt32(theDV[0]["DispensingId"]);
                theDispensingUnitName = theDV[0]["DispensingUnit"].ToString();
                theFunded = Convert.ToInt32(theDV[0]["Funded"]);
                theAvailQty = Convert.ToInt32(theDV[0]["AvailQty"]);
                theStrength = Convert.ToInt32(theDV[0]["StrengthId"]);
                theItemType = Convert.ToInt32(theDV[0]["DrugTypeId"]);
                if (theItemType == 37 && cmbprogram.SelectedValue.ToString() == "223")
                    theProphylaxis = 1;
                else
                    theProphylaxis = 0;
                theGenericAbb = theDV[0]["GenericAbb"].ToString();
                lstSearch.Visible = false;
                cmbFrequency.Select();
            }
        }

        private void cmbFrequency_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtQtyDispensed.Select();
            }
        }

        private void txtQtyDispensed_KeyUp(object sender, KeyEventArgs e)
        {
            if (txtQtyDispensed.Text.Trim()!= "")
            {
                string s = txtQtyDispensed.Text;
                if (s.IndexOf('.', 0) != -1)
                {
                    s = s.Substring(0, s.IndexOf('.', 0));
                }
                txtQtyDispensed.Text = s;
                if (txtQtyDispensed.Text == "0")
                {
                    txtQtyDispensed.Text = "";
                    IQCareWindowMsgBox.ShowWindowConfirm("QuanitytData", this);
                    return;
                }


                if (Convert.ToInt32(txtQtyDispensed.Text) > theAvailQty)
                {
                    IQCareWindowMsgBox.ShowWindow("DrugDispenseQtyCompare", this);
                    return;
                }
                CalculateSellingPrice();
            }
            if (e.KeyCode == Keys.Enter)
            {
                btnDispenseSubmit.Select();
            }
        }

        private void CalculateSellingPrice()
        {
            Int32 theQtyDispense = 0;
            if (theSellingPrice ==0)
            {
                IQCareWindowMsgBox.ShowWindowConfirm("MissingSellingPrice", this);
                return;
            }
            if (txtQtyDispensed.Text == "")
                theQtyDispense = 0;
            else
                theQtyDispense = Convert.ToInt32(txtQtyDispensed.Text);
            txtSellingPrice.Text = (theQtyDispense * theSellingPrice).ToString();
            if (theFunded == 0)
                theBillAmt = Convert.ToDecimal(txtSellingPrice.Text);
            else
                theBillAmt = Convert.ToDecimal("0");
        }

        private void btnDispenseSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateDrugDispense() == false)
                    return;
              

                if (txtItemName.Enabled == false)
                {
                    DataTable theDT = (DataTable)grdDrugDispense.DataSource;
                    DataView theDV = new DataView(theDT);
                    theDV.RowFilter = "ItemId = " + theItemId.ToString() + " and BatchId = " + theBatchId.ToString() + " and ExpiryDate='" + Convert.ToDateTime(txtExpirydate.Text) + "'";
                    if (theDV.Count > 0)
                    {
                        theDV[0]["QtyDisp"] = txtQtyDispensed.Text;
                        theDV[0]["FrequencyId"] = Convert.ToInt32(cmbFrequency.SelectedValue);
                        theDV[0]["FrequencyName"] = cmbFrequency.Text;
                        theDV[0]["SellingPrice"] = txtSellingPrice.Text;
                    }
                    txtItemName.Enabled = true;
                    BindPharmacyDispenseGrid(theDT);
                }
                else
                {
                    DataTable theDT = (DataTable)grdDrugDispense.DataSource;
                    if (theOrderStatus == "New Order")
                    {
                        DataRow []theRmDR = theDT.Select("ItemId = " + theItemId.ToString());
                        theDT.Rows.Remove(theRmDR[0]);
                    }

                  

                    // Check Total Quantity  (Available qty and enter Quantity)
                    if (thePrecribeAmt != 0)
                    {
                        if (theOrderStatus == "Partial Dispense")
                        {
                            decimal totalQuantity = 0;
                            decimal totalItemQty = 0;
                            DataView dv = theDT.DefaultView;
                            dv.RowFilter = "ItemId = " + theItemId.ToString();
                            DataTable dtnew = dv.ToTable();
                            foreach (DataRow dr in dtnew.Rows)
                            {
                                totalItemQty = totalItemQty + Convert.ToDecimal(dr[10].ToString());
                            }
                            if (dtnew.Rows.Count == 1 && totalItemQty == 0)
                            {
                                DataRow[] theRmDR = theDT.Select("ItemId = " + theItemId.ToString());
                                theDT.Rows.Remove(theRmDR[0]);
                                string s = txtQtyDispensed.Text;
                                if (s.IndexOf('.', 0) != -1)
                                {
                                    s = s.Substring(0, s.IndexOf('.', 0));
                                }
                                txtQtyDispensed.Text = s;
                                if (txtQtyDispensed.Text == "0")
                                {
                                    txtQtyDispensed.Focus();
                                    IQCareWindowMsgBox.ShowWindowConfirm("QuanitytData", this);
                                    return;
                                }
                            }
                            totalQuantity = totalItemQty + Convert.ToDecimal(txtQtyDispensed.Text);
                            if (totalQuantity > thePrecribeAmt)
                            {
                                IQCareWindowMsgBox.ShowWindowConfirm("QuanitytDetails", this);
                                return;
                            }
                        }
                    }

                    DataRow theDR = theDT.NewRow();
                    theDR["ItemId"] = theItemId;
                    theDR["ItemName"] = txtItemName.Text;
                    theDR["DispensingUnitId"] = theDispensingUnit;
                    theDR["DispensingUnitName"] = theDispensingUnitName;
                    theDR["BatchId"] = theBatchId;
                    theDR["BatchNo"] = txtBatchNo.Text;
                    theDR["ExpiryDate"] = txtExpirydate.Text;
                    theDR["QtyDisp"] = txtQtyDispensed.Text;
                    theDR["CostPrice"] = theCostPrice;
                    theDR["Margin"] = theMargin;
                    theDR["SellingPrice"] = txtSellingPrice.Text;
                    theDR["BillAmount"] = theBillAmt;
                    theDR["StrengthId"] = theStrength;
                    theDR["FrequencyId"] = Convert.ToInt32(cmbFrequency.SelectedValue);
                    theDR["FrequencyName"] = cmbFrequency.Text;
                    theDR["Prophylaxis"] = theProphylaxis;
                    theDR["ItemType"] = theItemType;
                    theDR["GenericAbb"] = theGenericAbb;

                    theDR["OrderedQuantity"] = thePrecribeAmt;// theDT1.Rows[0]["OrderedQuantity"].ToString();

                    theDR["DataStatus"] = "1";
                    

                    lblPayAmount.Text = (Convert.ToDecimal(lblPayAmount.Text) + theBillAmt).ToString();
                    theDT.Rows.Add(theDR);
                    BindPharmacyDispenseGrid(theDT);
                }
                theItemId = 0;
                theDispensingUnit = 0;
                theBatchId = 0;
                theCostPrice = 0;
                theMargin = 0;
                theBillAmt = 0;
                theDispensingUnitName = "";
                txtItemName.Text = "";
                txtBatchNo.Text = "";
                cmbFrequency.SelectedValue = "0";
                txtQtyDispensed.Text = "";
                txtExpirydate.Text = "";
                txtSellingPrice.Text = "";
                txtItemName.Select();
            }
            catch (Exception err)
            {
                MsgBuilder theBuilder = new MsgBuilder();
                theBuilder.DataElements["MessageText"] = err.Message.ToString();
                IQCareWindowMsgBox.ShowWindowConfirm("#C1", theBuilder, this);
            }
        }

        private Boolean ValidateDrugDispense()
        {
            if (txtItemName.Text.Trim() == "")
            {
                MsgBuilder theBuilder = new MsgBuilder();
                theBuilder.DataElements["Control"] = "Drug Name";
                IQCareWindowMsgBox.ShowWindowConfirm("BlankTextBox", theBuilder, this);
                return false;
            }
            if (Convert.ToInt32(cmbFrequency.SelectedValue) < 1)
            {
                MsgBuilder theBuilder = new MsgBuilder();
                theBuilder.DataElements["Control"] = "Frequency";
                IQCareWindowMsgBox.ShowWindowConfirm("BlankDropDown", theBuilder, this);
                return false;
            }
            if (Convert.ToInt32(cmbprogram.SelectedValue) < 1)
            {
                MsgBuilder theBuilder = new MsgBuilder();
                theBuilder.DataElements["Control"] = "Program";
                IQCareWindowMsgBox.ShowWindowConfirm("BlankDropDown", theBuilder, this);
                return false;
            }
            if (txtQtyDispensed.Text.Trim() == "")
            {
                MsgBuilder theBuilder = new MsgBuilder();
                theBuilder.DataElements["Control"] = "Quantity Dispensed";
                IQCareWindowMsgBox.ShowWindowConfirm("BlankTextBox", theBuilder, this);
                return false;
            }

            return true;
        }

        private void txtItemName_KeyPress(object sender, KeyPressEventArgs e)
        {
            BindFunctions theBindManager = new BindFunctions();
            theBindManager.Win_String(e);
        }

        private void txtQtyDispensed_KeyPress(object sender, KeyPressEventArgs e)
        {
            BindFunctions theBindManager = new BindFunctions();
            theBindManager.Win_Numeric(e);
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmdSave_Click(object sender, EventArgs e)
        {
            try
            {
             

                IDrug thePharmacyManager = (IDrug)ObjectFactory.CreateInstance("BusinessProcess.SCM.BDrug, BusinessProcess.SCM");
                if (tabDispense.TabPages[1].Focus() == true)
                {
                    DataTable theDT = (DataTable)grdDrugDispense.DataSource;
                    string theRegimen = "";
                    Int32 theProgId = 0;
                    Int32 theAge = Convert.ToDateTime(dtDispensedDate.Text).Year - theDOB.Year;
                    if (theAge > 15)
                        theProgId = 116;
                    else
                        theProgId = 117;

                    foreach (DataRow theDR in theDT.Rows)
                    {
                        if (theDR["ItemType"].ToString() == "37" && theDR["Prophylaxis"].ToString() != "1")
                        {
                            if (theRegimen == "" && theDR["GenericAbb"].ToString() != "")
                                theRegimen = theRegimen + theDR["GenericAbb"].ToString();
                            else if (theRegimen != "" && theDR["GenericAbb"].ToString() != "")
                                theRegimen = theRegimen + "/" + theDR["GenericAbb"].ToString();
                        }
                    }
                    thePharmacyManager.SavePharmacyDispense(thePatientId, GblIQCare.AppLocationId, GblIQCare.intStoreId, GblIQCare.AppUserId,
                        Convert.ToDateTime(dtDispensedDate.Text), theProgId, Convert.ToInt32(cmbprogram.SelectedValue), theRegimen,theOrderId, theDT);
                    IQCareWindowMsgBox.ShowWindow("PharmacyDispenseSave", this);
                    DataTable theNewDT = CreatePharmacyDispenseTable();
                    BindPharmacyDispenseGrid(theNewDT);
                    grdDrugDispense.DataSource = theNewDT;
                    theOrderId = 0;
                    theOrderStatus = "";
                }
                else if (tabDispense.TabPages[2].Focus() == true)
                {

                    if (Convert.ToDateTime(dtpReturnDate.Text) < Convert.ToDateTime(dtDispensedDate.Text))
                    {
                        IQCareWindowMsgBox.ShowWindow("NoDrugReturnDate", this);
                        return;
                    }
                    DataTable theDT = (DataTable)grdReturnDetail.DataSource;
                    int theRowsforSave = 0;
                    foreach (DataRow theDR in theDT.Rows)
                    {
                        if (Convert.ToInt32(theDR["ReturnQty"]) > 0)
                        {
                            theRowsforSave = theRowsforSave + 1;
                            theDR["SellingPrice"] = Convert.ToDecimal("-" + theDR["UnitSellingPrice"].ToString()) * Convert.ToInt32(theDR["ReturnQty"]);
                            if (Convert.ToInt32(theDR["BillAmount"]) > 0)
                            {
                                theDR["BillAmount"] = theDR["SellingPrice"];
                            }
                            else
                            {
                                theDR["BillAmount"] = 0;
                            }
                        }
                    }

                    if (theRowsforSave == 0)
                    {
                        IQCareWindowMsgBox.ShowWindow("NoDrugReturn", this);
                        return;
                    }
                    thePharmacyManager.SavePharmacyReturn(thePatientId, GblIQCare.AppLocationId, GblIQCare.intStoreId, Convert.ToDateTime(dtpReturnDate.Text), GblIQCare.AppUserId, theReturnOrderId, theDT);
                    IQCareWindowMsgBox.ShowWindow("PharmacyReturnSave", this);
                    theDT = thePharmacyManager.GetPharmacyExistingRecord(thePatientId,GblIQCare.intStoreId);
                    BindDrugReturnGrid(theDT);
                    grdReturnDetail.DataSource = false;
                    grdReturnDetail.Columns.Clear();
                }
                thePharmacyMaster = thePharmacyManager.GetPharmacyDispenseMasters(thePatientId, GblIQCare.intStoreId);
            }
            catch(Exception err)
            {
                MsgBuilder theBuilder = new MsgBuilder();
                theBuilder.DataElements["MessageText"] = err.Message.ToString();
                IQCareWindowMsgBox.ShowWindowConfirm("#C1", theBuilder, this);
            }
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            grpExistingRec.Visible = true;
            grpExistingRec.Left = 68;
            grpExistingRec.Top = 56;
            grpExistingRec.Width = 702;
            grpExistingRec.Height = 280;




            IDrug thePharmacyManager = (IDrug)ObjectFactory.CreateInstance("BusinessProcess.SCM.BDrug, BusinessProcess.SCM");
            DataTable theDT = thePharmacyManager.GetPharmacyExistingRecord(thePatientId,GblIQCare.intStoreId);
            BindExitingGrid(theDT);
        }

        private void BindExitingGrid(DataTable theDT)
        {
            grdExitingPharDisp.DataSource = null;
            grdExitingPharDisp.Columns.Clear();
            grdExitingPharDisp.AutoGenerateColumns = false;

            DataGridViewTextBoxColumn theCol1 = new DataGridViewTextBoxColumn();
            theCol1.HeaderText = "Transaction Date";
            theCol1.DataPropertyName = "TransactionDate";
            theCol1.Width = 200;

            DataGridViewTextBoxColumn theCol2 = new DataGridViewTextBoxColumn();
            theCol2.HeaderText = "Status";
            theCol2.DataPropertyName = "Status";
            theCol2.Width = 200;

            DataGridViewTextBoxColumn theCol3 = new DataGridViewTextBoxColumn();
            theCol3.HeaderText = "Id";
            theCol3.DataPropertyName = "Ptn_Pharmacy_Pk";
            theCol3.Width = 10;
            theCol3.Visible = false;

            grdExitingPharDisp.Columns.Add(theCol1);
            grdExitingPharDisp.Columns.Add(theCol2);
            grdExitingPharDisp.Columns.Add(theCol3);
            grdExitingPharDisp.DataSource = theDT;

        }

        private void BindDrugReturnGrid(DataTable theDT)
        {
            grdReturnOrder.DataSource = null;
            grdReturnOrder.Columns.Clear();
            grdReturnOrder.AutoGenerateColumns = false;

            DataGridViewTextBoxColumn theCol1 = new DataGridViewTextBoxColumn();
            theCol1.HeaderText = "Transaction Date";
            theCol1.DataPropertyName = "TransactionDate";
            theCol1.Width = 200;

            DataGridViewTextBoxColumn theCol2 = new DataGridViewTextBoxColumn();
            theCol2.HeaderText = "Status";
            theCol2.DataPropertyName = "Status";
            theCol2.Width = 200;

            DataGridViewTextBoxColumn theCol3 = new DataGridViewTextBoxColumn();
            theCol3.HeaderText = "Id";
            theCol3.DataPropertyName = "Ptn_Pharmacy_Pk";
            theCol3.Width = 10;
            theCol3.Visible = false;

            grdReturnOrder.Columns.Add(theCol1);
            grdReturnOrder.Columns.Add(theCol2);
            grdReturnOrder.Columns.Add(theCol3);
            grdReturnOrder.DataSource = theDT;
        }

        private void btnExitingRecClose_Click(object sender, EventArgs e)
        {
            grpExistingRec.Visible = false;
        }

        private void grdExitingPharDisp_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            theOrderId = Convert.ToInt32(grdExitingPharDisp.Rows[grdExitingPharDisp.CurrentRow.Index].Cells[2].Value);
            theOrderStatus = grdExitingPharDisp.Rows[grdExitingPharDisp.CurrentRow.Index].Cells[1].Value.ToString();
            IDrug thePharmacyManager = (IDrug)ObjectFactory.CreateInstance("BusinessProcess.SCM.BDrug, BusinessProcess.SCM");
            DataSet theDS = thePharmacyManager.GetPharmacyExistingRecordDetails(theOrderId);
            if (theDS.Tables[1].Rows.Count > 0)
            {
                if (theDS.Tables[1].Rows[0].IsNull("DispensedByDate") == false)
                    dtDispensedDate.Text = theDS.Tables[1].Rows[0]["DispensedByDate"].ToString();
                if (theDS.Tables[1].Rows[0].IsNull("ProgId") == false)
                    cmbprogram.SelectedValue = theDS.Tables[1].Rows[0]["ProgId"].ToString();
            }
            decimal theBillAmount = 0;
            foreach (DataRow theRow in theDS.Tables[0].Rows)
            {
                if (theRow.IsNull("BillAmount") == false)
                    theBillAmount = theBillAmount + Convert.ToDecimal(theRow["BillAmount"]);
                else
                    theBillAmount = theBillAmount + 0;
            }
            lblPayAmount.Text = theBillAmount.ToString();
            BindPharmacyDispenseGrid(theDS.Tables[0]);
            
            // todo
            //if (theDS.Tables[0].Rows[0]["OrderedQuantity"].ToString() != null && theDS.Tables[0].Rows[0]["OrderedQuantity"].ToString() != "")
            //{
            //    thePrecribeAmt = Convert.ToDecimal(theDS.Tables[0].Rows[0]["OrderedQuantity"]);
            //}

            grpExistingRec.Visible = false;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            thePrecribeAmt = 0;
            theOrderId = 0;
            DataTable theNewDT = CreatePharmacyDispenseTable();
            grdDrugDispense.DataSource = theNewDT;
            BindPharmacyDispenseGrid(theNewDT);
            dtDispensedDate.Text = GblIQCare.CurrentDate;
            cmbprogram.SelectedValue = "0";
            theItemId = 0;
            theDispensingUnit = 0;
            theBatchId = 0;
            theCostPrice = 0;
            theMargin = 0;
            theBillAmt = 0;
            theDispensingUnitName = "";
            txtItemName.Text = "";
            txtBatchNo.Text = "";
            cmbFrequency.SelectedValue = "0"; 
            txtQtyDispensed.Text = "";
            txtExpirydate.Text = "";
            txtSellingPrice.Text = "";
            txtItemName.Select();
        }

        private void grdDrugDispense_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int PresdispenceQty = 0;
            decimal totalOqdQty = 0;
            if (grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[8].Value.ToString() != "" && grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[8].Value.ToString() != "0")
            {
                if (!Convert.ToInt32(grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[8].Value).Equals(System.DBNull.Value))
                {
                    PresdispenceQty = Convert.ToInt32(grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[8].Value);

                    thePrecribeAmt = PresdispenceQty;

                    string itemID = grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[0].Value.ToString();
                    DataTable dtGrd = ((DataTable)(grdDrugDispense.DataSource)).Copy();
                    DataView dv = dtGrd.DefaultView;
                    dv.RowFilter = "ItemId=" + itemID;

                    DataTable dt1 = dv.ToTable();// Table;
                  
                    foreach (DataRow dr in dt1.Rows)
                    {
                        totalOqdQty = totalOqdQty + Convert.ToDecimal(dr["QtyDisp"].ToString());
                    }
                    if (PresdispenceQty <= totalOqdQty)
                    {
                        IQCareWindowMsgBox.ShowWindow("PharmacyCannotAlterRow", this);
                        return;
                    }
                }
            }
            else if (theOrderId > 0 && theOrderStatus != "New Order")
            {
                IQCareWindowMsgBox.ShowWindow("PharmacyCannotAlterRow", this);
                return;
            }
            theItemId = Convert.ToInt32(grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[0].Value);
            DataView theDV = new DataView(thePharmacyMaster.Tables[1]);

            // Add && theOrderStatus != "Partial Dispense"  below line
            if (theOrderStatus != "New Order" && theOrderStatus != "Partial Dispense")
            {
                theDV.RowFilter = "Drug_Pk = " + theItemId.ToString() + " and BatchId = " + grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[4].Value.ToString() +
                    " and ExpiryDate='" + grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[6].Value.ToString() + "'";
            }
            else
            {
                theDV.RowFilter = "Drug_Pk = " + theItemId.ToString();
            }
            if ((theDV.ToTable().Rows.Count == 0) && (Convert.ToInt32(grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[9].Value)==0))
            {
                IQCareWindowMsgBox.ShowWindow("NoAvailQty", this);
                return;
            }
            else
            {
                txtItemName.Text = theDV[0]["DrugName"].ToString();
                if (theOrderStatus == "New Order")
                {
                    txtQtyDispensed.Text = "";
                    cmbFrequency.SelectedValue = grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[14].Value.ToString();
                    txtSellingPrice.Text = "";
                    txtBatchNo.Text = "";
                    theBatchId = 0;
                    txtExpirydate.Text = "";
                    theSellingPrice = 0;
                    theCostPrice = 0;
                    theMargin = 0;
                    theDispensingUnit = 0;
                    theDispensingUnitName = "";
                    theFunded = 0;
                    theAvailQty = 0;
                    theStrength = 0;
                    theItemType = Convert.ToInt32(theDV[0]["DrugTypeId"]);
                    txtItemName.Select();
                    KeyEventArgs theArg = new KeyEventArgs(Keys.Enter);
                    txtItemName_KeyUp(txtItemName, theArg);

                }
                else
                {
                    txtBatchNo.Text = theDV[0]["BatchNo"].ToString();
                    theBatchId = Convert.ToInt32(theDV[0]["BatchId"]);
                    txtExpirydate.Text = ((DateTime)theDV[0]["ExpiryDate"]).ToString(GblIQCare.AppDateFormat);
                    theSellingPrice = Convert.ToDecimal(theDV[0]["SellingPrice"]);
                    theCostPrice = Convert.ToDecimal(theDV[0]["CostPrice"]);
                    theMargin = Convert.ToDecimal(theDV[0]["DispensingMargin"]);
                    theDispensingUnit = Convert.ToInt32(theDV[0]["DispensingId"]);
                    theDispensingUnitName = theDV[0]["DispensingUnit"].ToString();
                    theFunded = Convert.ToInt32(theDV[0]["Funded"]);
                    theAvailQty = Convert.ToInt32(theDV[0]["AvailQty"]);
                    theStrength = Convert.ToInt32(theDV[0]["StrengthId"]);
                    theItemType = Convert.ToInt32(theDV[0]["DrugTypeId"]);
                    txtQtyDispensed.Text = Convert.ToDecimal(grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[7].Value).ToString();
                    cmbFrequency.SelectedValue = grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[15].Value.ToString();


                    if (grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[12].Value.ToString() != "")
                    {
                        if (!Convert.ToInt32(grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[12].Value).Equals(System.DBNull.Value))
                        {
                            txtSellingPrice.Text = Convert.ToDecimal(grdDrugDispense.Rows[grdDrugDispense.CurrentRow.Index].Cells[12].Value).ToString();
                        }
                    }
                    if (PresdispenceQty > totalOqdQty)
                    {
                        txtItemName.Enabled = true;
                    }
                    else
                    {
                        txtItemName.Enabled = false;
                    }


                    if (theItemType == 37 && cmbprogram.SelectedValue.ToString() == "223")
                        theProphylaxis = 1;
                    else
                        theProphylaxis = 0;
                    theGenericAbb = theDV[0]["GenericAbb"].ToString();

                }
            }
        }

        private void grdReturnOrder_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (grdReturnOrder.Rows[grdReturnOrder.CurrentRow.Index].Cells[1].Value.ToString() != "New Order")
            {
                theReturnOrderId = Convert.ToInt32(grdReturnOrder.Rows[grdReturnOrder.CurrentRow.Index].Cells[2].Value);
                IDrug thePharmacyManager = (IDrug)ObjectFactory.CreateInstance("BusinessProcess.SCM.BDrug, BusinessProcess.SCM");
                DataSet theDS = thePharmacyManager.GetPharmacyExistingRecordDetails(theReturnOrderId);
                lblReturnDispensedDate.Text = ((DateTime)theDS.Tables[1].Rows[0]["DispensedByDate"]).ToString("dd-MMM-yyyy");
                DataView theDV = new DataView(XMLDS.Tables["Mst_Decode"]);
                theDV.RowFilter = "CodeId = 33 and (DeleteFlag = 0 or DeleteFlag is null) and Id = " + theDS.Tables[1].Rows[0]["ProgId"].ToString();
                lblReturnProgram.Text = theDV[0]["Name"].ToString();
                DataTable theReturnDT = theDS.Tables[0];
                BindDrugRetunDetailGrid(theDS.Tables[0]);
            }
        }

        private void BindDrugRetunDetailGrid(DataTable theDT)
        {
            grdReturnDetail.DataSource = null;
            grdReturnDetail.Columns.Clear();
            grdReturnDetail.AutoGenerateColumns = false;

            DataGridViewTextBoxColumn theCol1 = new DataGridViewTextBoxColumn();
            theCol1.HeaderText = "ItemId";
            theCol1.DataPropertyName = "ItemId";
            theCol1.Width = 10;
            theCol1.Visible = false;

            DataGridViewTextBoxColumn theCol2 = new DataGridViewTextBoxColumn();
            theCol2.HeaderText = "Drug Name";
            theCol2.DataPropertyName = "ItemName";
            theCol2.Width = 200;
            theCol2.ReadOnly = true; 

            DataGridViewTextBoxColumn theCol3 = new DataGridViewTextBoxColumn();
            theCol3.HeaderText = "DispUnitId";
            theCol3.DataPropertyName = "DispensingUnitId";
            theCol3.Width = 10;
            theCol3.Visible = false;

            DataGridViewTextBoxColumn theCol4 = new DataGridViewTextBoxColumn();
            theCol4.HeaderText = "Dispensing Unit";
            theCol4.DataPropertyName = "DispensingUnitName";
            theCol4.Width = 80;
            theCol4.ReadOnly = true; 

            DataGridViewTextBoxColumn theCol5 = new DataGridViewTextBoxColumn();
            theCol5.HeaderText = "BatchId";
            theCol5.DataPropertyName = "BatchId";
            theCol5.Width = 10;
            theCol5.Visible = false;

            DataGridViewTextBoxColumn theCol6 = new DataGridViewTextBoxColumn();
            theCol6.HeaderText = "Batch No";
            theCol6.DataPropertyName = "BatchNo";
            theCol6.Width = 80;
            theCol6.ReadOnly = true; 

            DataGridViewTextBoxColumn theCol7 = new DataGridViewTextBoxColumn();
            theCol7.HeaderText = "Expiry Date";
            theCol7.DataPropertyName = "ExpiryDate";
            theCol7.Width = 80;
            theCol7.ReadOnly = true; 

            DataGridViewTextBoxColumn theCol8 = new DataGridViewTextBoxColumn();
            theCol8.HeaderText = "Quantity";
            theCol8.DataPropertyName = "QtyDisp";
            theCol8.Width = 80;
            theCol8.ReadOnly = true; 

            DataGridViewTextBoxColumn theCol9 = new DataGridViewTextBoxColumn();
            theCol9.HeaderText = "CostPrice";
            theCol9.DataPropertyName = "CostPrice";
            theCol9.Width = 10;
            theCol9.Visible = false;

            DataGridViewTextBoxColumn theCol10 = new DataGridViewTextBoxColumn();
            theCol10.HeaderText = "Margin";
            theCol10.DataPropertyName = "Margin";
            theCol10.Width = 10;
            theCol10.Visible = false;

            DataGridViewTextBoxColumn theCol11 = new DataGridViewTextBoxColumn();
            theCol11.HeaderText = "Selling Price";
            theCol11.DataPropertyName = "SellingPrice";
            theCol11.Width = 80;
            theCol11.Visible = false; 

            DataGridViewTextBoxColumn theCol12 = new DataGridViewTextBoxColumn();
            theCol12.HeaderText = "Bill Amount";
            theCol12.DataPropertyName = "BillAmount";
            theCol12.Width = 80;
            theCol12.Visible = false; 

            DataGridViewTextBoxColumn theCol13 = new DataGridViewTextBoxColumn();
            theCol13.HeaderText = "StrengthId";
            theCol13.DataPropertyName = "StrengthId";
            theCol13.Width = 10;
            theCol13.Visible = false;

            DataGridViewTextBoxColumn theCol14 = new DataGridViewTextBoxColumn();
            theCol14.HeaderText = "Frequency";
            theCol14.DataPropertyName = "FrequencyId";
            theCol14.Width = 10;
            theCol14.Visible = false;

            DataGridViewTextBoxColumn theCol15 = new DataGridViewTextBoxColumn();
            theCol15.HeaderText = "Frequency";
            theCol15.DataPropertyName = "FrequencyName";
            theCol15.Width = 80;
            theCol15.Visible = false; 

            DataGridViewTextBoxColumn theCol16 = new DataGridViewTextBoxColumn();
            theCol16.HeaderText = "Quantity Return";
            theCol16.DataPropertyName = "ReturnQty";
            theCol16.Width = 80;

            DataView theDV = new DataView(XMLDS.Tables["Mst_Decode"]);
            theDV.RowFilter = "CodeId = 204 and (DeleteFlag = 0 or DeleteFlag is null)";
            DataTable theReturnReasonDT = theDV.ToTable();
            DataGridViewComboBoxColumn theCol17 = new DataGridViewComboBoxColumn();
            theCol17.HeaderText = "Return Reason";
            theCol17.ValueMember = "Id";
            theCol17.DisplayMember = "Name";
            theCol17.DataSource = theReturnReasonDT; 
            theCol17.DataPropertyName = "ReturnReason";
            theCol17.Width = 150;

            grdReturnDetail.Columns.Add(theCol1);
            grdReturnDetail.Columns.Add(theCol2);
            grdReturnDetail.Columns.Add(theCol3);
            grdReturnDetail.Columns.Add(theCol4);
            grdReturnDetail.Columns.Add(theCol5);
            grdReturnDetail.Columns.Add(theCol6);
            grdReturnDetail.Columns.Add(theCol7);
            grdReturnDetail.Columns.Add(theCol8);
            grdReturnDetail.Columns.Add(theCol15);
            grdReturnDetail.Columns.Add(theCol9);
            grdReturnDetail.Columns.Add(theCol10);
            grdReturnDetail.Columns.Add(theCol11);
            grdReturnDetail.Columns.Add(theCol12);
            grdReturnDetail.Columns.Add(theCol13);
            grdReturnDetail.Columns.Add(theCol14);
            grdReturnDetail.Columns.Add(theCol16);
            grdReturnDetail.Columns.Add(theCol17);

            grdReturnDetail.DataSource = theDT;

        }

        private void grdReturnDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control.GetType().ToString() == "System.Windows.Forms.DataGridViewTextBoxEditingControl")
            {
                theCurrentRow = grdReturnDetail.CurrentRow.Index;
                theReturnQty = (TextBox)e.Control;
                theReturnQty.KeyUp += new KeyEventHandler(theReturnQty_KeyUp);
                theReturnQty.KeyPress += new KeyPressEventHandler(theReturnQty_KeyPress);
            }
        }

        void theReturnQty_KeyUp(object sender, KeyEventArgs e)
        {
            if (theReturnQty.Text != "")
            {
                if (Convert.ToInt32(grdReturnDetail.Rows[theCurrentRow].Cells[7].Value) < Convert.ToInt32(theReturnQty.Text))
                {
                    IQCareWindowMsgBox.ShowWindow("ReturnQtyGrtthanIssue", this);
                    theReturnQty.Text = "";
                    return;
                }
            }
        }

        void theReturnQty_KeyPress(object sender, KeyPressEventArgs e)
        {
            BindFunctions theBindManager = new BindFunctions();
            theBindManager.Win_Numeric(e);
        }

        private void grdResultView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
